'use strict';

// https://help.aliyun.com/document_detail/32068.html

const Controller = require('egg').Controller;
const fs = require('mz/fs');
let OSS = require('ali-oss');

let aliInfo = {
  // https://help.aliyun.com/document_detail/31837.html
  region: 'oss-cn-shenzhen',
  bucket: 'qixiwximg',
  accessKeyId: 'LTAIOL60W1RI80wB',
  accessKeySecret: 'IKH9qiA0Cl9Pg2YpjhMeIEAdWqltHi'
}

let client = new OSS(aliInfo);

class AliOssController extends Controller {
  async upload() {
    const { ctx } = this;
    const file = ctx.request.files[0];
    let result;
    try {
      // 处理文件，比如上传到云端
      result = await client.put(file.filename, file.filepath);
    } finally {
      // 需要删除临时文件
      await fs.unlink(file.filepath);
    }
    ctx.body = {
      url: result.url,
      // 获取所有的字段值
      requestBody: result,
    };
  }
}

module.exports = AliOssController;
